<template>
  <div style="height: 100%">
    <div class="top-bar">
      <el-button type="primary" @click="addXm()">新增</el-button>
    </div>
    <el-table
        :data="xmList"
        stripe
        height="calc(100% - 28px)"
        style="width: 100%">
      <el-table-column
          label="序号"
          type="index"
          width="50">
      </el-table-column>
      <el-table-column
          label="项目名称"
          show-overflow-tooltip>
        <template slot-scope="{row}">
          <el-link type="primary" @click="intoXm(row)">{{ row.xmmc }}</el-link>
        </template>
      </el-table-column>
      <el-table-column
          label="创建人员名称"
          prop="rymc"
          width="150px">
      </el-table-column>
      <el-table-column
          label="创建时间"
          prop="cjsj"
          width="150px">
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          width="330px">
        <template slot-scope="{row}">
          <el-popover
              placement="bottom"
              title="请选择导出类型"
              width="200"
              style="margin-right: 10px"
              trigger="click">
            <el-button type="primary" @click="dcGz(row,'1')">sql语句</el-button>
            <el-button type="primary" @click="dcGz(row,'0')">规则包</el-button>
            <el-button slot="reference" type="primary">导出规则</el-button>
          </el-popover>
          <el-button @click="drGz(row)" v-show="isAdmin">导入规则</el-button>
          <el-button @click="addXm(row)">编辑</el-button>
          <el-button type="danger" @click="preDel(deleteXm,row)" v-show="row.sfsc==='N'">删除</el-button>
          <el-button type="primary" @click="undeleteXm(row)" v-show="row.sfsc==='Y'">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>
    <xj-dialog :title="(xmForm.xmbm?'编辑':'新增')+'项目'"
               width="80%"
               :visible="addXmDialogVisible">
      <el-form :model="xmForm" label-width="70px">
        <el-form-item label="项目名称">
          <el-input v-model="xmForm.xmmc"></el-input>
        </el-form-item>
        <el-button type="primary" @click="addNewItem">添加项目配置项</el-button>
        <el-table
            stripe
            :data="xmForm.xmpz"
            style="width: 100%">
          <el-table-column
              type="index"
              label="序号">
          </el-table-column>
          <el-table-column
              label="编码"
              width="180">
            <template slot-scope="{row}">
              <el-input v-model="row.bm"></el-input>
            </template>
          </el-table-column>
          <el-table-column
              label="名称"
              width="180">
            <template slot-scope="{row}">
              <el-input v-model="row.mc"></el-input>
            </template>
          </el-table-column>
          <el-table-column
              label="类型">
            <template slot-scope="{row}">
              <el-select v-model="row.lx">
                <el-option
                    v-for="(v,k) in lxObj"
                    :key="k"
                    :label="v"
                    :value="k">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
              label="默认值"
              width="180">
            <template slot-scope="{row}">
              <div v-show="row.lx!=='input'">
                <el-select v-model="row.mrz">
                  <el-option
                      v-for="item in  row.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div v-show="row.lx==='input'">
                <el-input v-model="row.mrz"></el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              label="配置"
              width="430">
            <template slot-scope="{row}">
              <div v-show="row.lx!=='input'">
                <el-form label-width="40px">
                  <div v-for="item in row.options"
                       style="display:grid;grid-template-columns: 200px 200px 30px;">
                    <el-form-item label="名称">
                      <el-input v-model="item.label"></el-input>
                    </el-form-item>
                    <el-form-item label="值">
                      <el-input v-model="item.value"></el-input>
                    </el-form-item>
                    <div class="delete-btn" title="删除" @click="removeOptionItem(row.options,item)"></div>
                  </div>
                </el-form>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              label="操作">
            <template slot-scope="{row}">

              <el-button v-show="row.lx!=='input'" type="primary" @click="row.options.push({label:'',value:''})">增加项
              </el-button>
              <el-button type="danger" @click="removeItem(xmForm.xmpz,row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer">
        <el-button @click="handleAddXmBtnClick(false)">取消</el-button>
        <el-button type="primary" @click="handleAddXmBtnClick(true)">确定</el-button>
      </div>
    </xj-dialog>
    <xj-dialog :title="`SQL-${sqlTitle}`"
               height="100%" width="calc(100% - 30vw)" :visible="!!sqlText">
      <code-editor
          :value="sqlText"
          style="height: 99%">
      </code-editor>
      <div slot="footer">
        <el-button type="primary" @click="downloadSql">保存到本地</el-button>
        <el-button @click="sqlText=''">关闭</el-button>
      </div>
    </xj-dialog>
  </div>
</template>

<script>
import commonMixins from "@/mixins/commonMixins";
import XjDialog from "@/components/XjDialog";
import CodeEditor from "@/components/CodeEditor";


function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {type: mime});
}

function downloadFile(url, name = '未命名文件') {
  let a = document.createElement("a")
  a.setAttribute("href", url)
  a.setAttribute("download", name)
  a.setAttribute("target", "_blank")
  let clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
}

function downloadFileByBase64(base64, name) {
  let myBlob = dataURLtoBlob(base64)
  downloadFileByBlob(myBlob, name)
}

function downloadFileByBlob(blob, name) {
  let myUrl = URL.createObjectURL(blob)
  downloadFile(myUrl, name)
}

function downloadFileByText(text, name) {
  let blob = new Blob([text], {type: 'text/plain'});
  downloadFileByBlob(blob, name)
}

export default {
  name: "Xmgl",
  components: {XjDialog, CodeEditor},
  mixins: [commonMixins],
  data() {
    return {
      lxObj: {
        'radio-button': '单选',
        'select': '下拉菜单',
        'input': '输入框',
      },
      xmList: [],
      xmForm: {
        xmbm: '',
        xmmc: '',
        xmpz: [],
      },
      addXmDialogVisible: false,
      sqlTitle: '',
      sqlText: '',
    }
  },
  mounted() {
    this.queryXmList();
  },
  methods: {
    async queryXmList() {
      let xmList = await this.$api.queryXmListByRybm({rybm: this.yhxx.rybm})
      this.xmList = xmList.map(xm => {
        return {
          ...xm,
          xmpz: JSON.parse(xm.xmpz || '[]')
        }
      })
    },
    addNewItem() {
      let hasEmpty = this.xmForm.xmpz.some(item => !item.bm)
      if (hasEmpty) {
        return this.$message({
          message: `存在空的编码`,
          type: "error"
        })
      }
      this.xmForm.xmpz.push({
        mc: '',
        bm: '',
        mrz: '',
        lx: 'input',
        options: []
      })
    },
    async dcGz(xm, dclx) {
      try {
        let response = await this.$api.dcGz({xmbm: xm.xmbm, dclx}, {responseType: 'blob'})
        this.sqlTitle = decodeURIComponent(response.headers['filename'])
        if (dclx === '0') {
          return downloadFileByBlob(response.data, this.sqlTitle)
        }
        let reader = new FileReader();
        reader.onload = e => this.sqlText = reader.result;
        reader.readAsText(response.data);
      } catch (e) {
        this.$message({message: `下载失败：${e.message}`, type: "error"})
      }
    },
    downloadSql() {
      downloadFileByText(this.sqlText, this.sqlTitle);
    },
    async drGz(xm) {
      try {
        return await new Promise((resolve, reject) => {
          let timer = setTimeout(() => {
            return reject(new Error("选取文件超时"))
          }, 60 * 1000)
          let input = document.createElement("input")
          input.type = "file"
          input.accept = "application/x-zip-compressed"
          input.onchange = async (e) => {
            if (timer) {
              clearTimeout(timer)
            }
            let file = input.files[0]
            if (file.type !== "application/x-zip-compressed") {
              return reject(new Error("选择的文件不是zip类型，请检查"))
            }
            // 开始导入
            let formData = new FormData()
            formData.append("xmbm", xm.xmbm)
            formData.append("file", file)
            let res = await this.$api.drGz(formData)
            console.log(res)
            this.$message({message: '导入成功', type: "success"})
            resolve()
          }
          input.click()
        })
      } catch (e) {
        this.$message({message: e.message, type: "error"})
      }
    },
    intoXm(xm) {
      mySessionStorage.setItem("xm-item", xm)
      this.$router.push(`/xmsy`)
    },
    async addXm(xm) {
      if (!xm) {
        xm = {
          xmbm: '',
          xmmc: '',
          xmpz: []
        }
      }
      this.xmForm = {xmpz: [], ...xm}
      this.addXmDialogVisible = true
    },
    removeOptionItem(options, option) {
      let idx = options.findIndex(opt => opt.label === option.label)
      if (idx > -1) {
        options.splice(idx, 1)
      }
    },
    removeItem(xtpz, pzItem) {
      let idx = xtpz.findIndex(item => item.bm === pzItem.bm)
      if (idx > -1) {
        xtpz.splice(idx, 1)
      }
    },
    async handleAddXmBtnClick(isConfirm) {
      if (isConfirm) {
        // 数据校验

        let xmpz = this.xmForm.xmpz
        for (let xmpzElement of xmpz) {
          if (!xmpzElement.mc) {
            return this.$message({
              message: `部分名称为空`,
              type: "error"
            })
          }
          if (!xmpzElement.bm) {
            return this.$message({
              message: `部分编码为空`,
              type: "error"
            })
          }
          if (xmpzElement.lx === 'radio-button' || xmpzElement.lx === 'select') {
            if (!xmpzElement.options.length) {
              return this.$message({
                message: `【${xmpzElement.mc}】的类型为【${this.lxObj[xmpzElement.lx]}】，配置不能为空`,
                type: "error"
              })
            }
            for (let option of xmpzElement.options) {
              if (!option.label) {
                return this.$message({
                  message: `【${xmpzElement.mc}】的部分配置名称为空`,
                  type: "error"
                })
              }
              if (!option.value) {
                return this.$message({
                  message: `【${xmpzElement.mc}】的部分配置值为空`,
                  type: "error"
                })
              }
            }
            if (xmpzElement.mrz) {
              let isOk = xmpzElement.options.some(item => item.value === xmpzElement.mrz)
              if (!isOk) {
                return this.$message({
                  message: `【${xmpzElement.mc}】的默认值【${this.lxObj[xmpzElement.lx]}】不正确，请检查！`,
                  type: "error"
                })
              }
            }
          }
        }

        // 进行保存
        try {
          if (this.xmForm.xmbm) {
            await this.$api.updateXm({
              xmbm: this.xmForm.xmbm,
              xmmc: this.xmForm.xmmc,
              xmpz: JSON.stringify(xmpz),
            })
          } else {
            await this.$api.addXm({
              xmmc: this.xmForm.xmmc,
              rybm: this.yhxx.rybm,
              rymc: this.yhxx.mc,
              xmpz: JSON.stringify(xmpz),
            })
          }
          this.queryXmList()
        } catch (e) {
          this.$message({message: e.message, type: 'error'})
          return
        }
      }
      this.addXmDialogVisible = false
      this.xmForm = {xmbm: '', xmmc: ''}
    },
    async deleteXm(xm) {
      try {
        await this.$api.deleteXm({xmbm: xm.xmbm})
        this.$message({message: "删除成功", type: 'success'})
        this.queryXmList()
      } catch (e) {
        this.$message({message: `删除失败：${e.message}`, type: 'error'})
      }
    },
    async undeleteXm(xm) {
      await this.$api.undeleteXm({xmbm: xm.xmbm})
      this.queryXmList()
    }
  }
}
</script>
<style scoped lang="scss">
.delete-btn {
  background-image: url("~@/assets/svg/delete.svg");
  background-repeat: no-repeat;
  background-position: center;
  width: 28px;
  height: 28px;
  cursor: pointer;
}
</style>
